package com.banciyuan.bcywebview.utils.sns.weibo;

import android.content.Context;
import android.text.TextUtils;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.apprecommend.RecommendAcgActivity;
import com.banciyuan.bcywebview.biz.register.PhoneRegisterActivity;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sns.SnsMemory;
import com.banciyuan.bcywebview.utils.sns.UsersAPI;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * weibo登陆工具类.
 *
 * @author hfxt2008
 */
public class WeiboLoginHelper {

    private Context mContext;
    private RequestQueue mQueue;

    private Oauth2AccessToken mAccessToken;
    private UsersAPI mUsersAPI;
    private SsoHandler mSsoHandler;
    private String sinaName;

    public WeiboLoginHelper(Context mContext, SsoHandler mSsoHandler) {
        this.mContext = mContext;
        this.mSsoHandler = mSsoHandler;
        mQueue = VolleyQueue.getRquest(mContext);
    }

    public void doWeiboLogin() {
        mSsoHandler.authorize(new AuthListener());
    }

    private void doWeiboLogin(String uid, String utoken, long etime) {

        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                String result = dealWeiboJson(response);
                if (result.equals(HttpUtils.UPLOAD_SUCCESS)) {
                    if (isShowRecommend()) {
                        gotoUtil.replaceMainClearTop(mContext);
                    } else {
                        gotoUtil.replaceAct(mContext, RecommendAcgActivity.class);
                    }
                } else if (result.equals(HttpUtils.UPLOAD_NODATA)) {
                    gotoUtil.replaceAct(mContext, PhoneRegisterActivity.class, true, sinaName);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                netWorkError();
            }
        };
        List<BcyPair> params = new ArrayList<>();
        params.add(new BcyPair(HttpUtils.SINA_PARAM_UID, uid));
        if (!TextUtils.isEmpty(sinaName))
            params.add(new BcyPair(HttpUtils.REGISTER_PARAM_SINANAME, sinaName));
        params.add(new BcyPair(HttpUtils.SINA_PARAM_TOKEN, utoken));
        params.add(new BcyPair(HttpUtils.SINA_PARAM_ETIME, String.valueOf(etime)));
        Map<String, String> map = HttpUtils.getData(params);
        StringRequestParam getUserdataRequest = new StringRequestParam(
                Method.POST, HttpUtils.BASE_URL + UserApi.getSinalogin(), map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
    }

    private boolean isShowRecommend() {
        return SPHelper.getBoolean(mContext, SPConstant.BCY_SHOWRECOMMEND, false);
    }

    private String dealWeiboJson(String result) {
        try {
            JSONObject response = new JSONObject(result);
            int status = response.getInt(HttpUtils.UPLOAD_STATUS);
            if (status == 1) {
                UserDataHelper.Login(response.getJSONObject(HttpUtils.UPLOAD_DATA), mContext);
                return HttpUtils.UPLOAD_SUCCESS;
            } else {
                MyToast.show(mContext, String.format(MyConstants.TOAST_FORMAT, response.getString(HttpUtils.UPLOAD_DATA)));
                return HttpUtils.UPLOAD_NODATA;
            }
        } catch (JSONException e) {
            netWorkError();
            return HttpUtils.UPLOAD_ERROR;
        }
    }

    private void netWorkError() {
        MyToast.show(mContext, mContext.getString(R.string.network_error));
    }

    private class AuthListener implements WbAuthListener {

        @Override
        public void onSuccess(Oauth2AccessToken oauth2AccessToken) {
            try {
                mAccessToken = oauth2AccessToken;
                if (mAccessToken.isSessionValid()) {
                    SnsMemory.mAccessToken = mAccessToken;
                    mUsersAPI = new UsersAPI(mContext, MyConstants.APP_KEY, mAccessToken);
                    Long mUid = Long.parseLong(mAccessToken.getUid());
                    final long etime = mAccessToken.getExpiresTime() / 1000;
                    mUsersAPI.getUserInfo(mQueue, String.valueOf(mUid), mAccessToken.getToken(), new UsersAPI.UserInfoListener() {
                        @Override
                        public void onError() {
                            doWeiboLogin(mAccessToken.getUid(), mAccessToken.getToken(), etime);
                            MyToast.show(mContext, mContext.getString(R.string.author_succ));
                        }

                        @Override
                        public void onComplete(String result) {
                            try {
                                JSONObject json = new JSONObject(result);
                                sinaName = json.getString("name");
                                doWeiboLogin(mAccessToken.getUid(), mAccessToken.getToken(), etime);
                                MyToast.show(mContext, mContext.getString(R.string.author_succ));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } else {
                    MyToast.show(mContext, mContext.getString(R.string.author_fail));
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void cancel() {
            MyToast.show(mContext, mContext.getString(R.string.author_cancel));

        }

        @Override
        public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {
            MyToast.show(mContext, mContext.getString(R.string.network_error));

        }
    }
}